<template>
  <div class="app-container">
    <!-- 视频播放 -->
    <div class="backgroundClass">
      <el-page-header @back="goback" :content="titleName"> </el-page-header>
    </div>
    <div style="padding-top: 0; margin-top: 24px; background: #fff">
      <div class="videoBigBox">
        <div class="videoBox" v-loading="loadingvideo">
          <div v-show="showVideo" style="padding-left: 12px; height: 100%">
            <video-player
              :class="
                isquerymodel
                  ? 'video-player vjs-custom-skin'
                  : 'video-player vjs-custom-skin isShowModel'
              "
              ref="videoPlayer"
              :playsinline="true"
              :options="playerOptions"
              @ended="onPlayerEnded($event)"
              @timeupdate="onPlayerTimeupdate($event)"
              @ready="playerReadied"
              v-loading="loading"
              v-if="!aliDom"
            >
            </video-player>
            <div
              v-loading="loading"
              id="J_prismPlayer"
              style="height: 100%"
              v-else
            ></div>
          </div>
          <div v-show="!showVideo" class="exemBox">
            <div v-if="tableData.length == 0" class="exemBoxShow">
              <a-empty
                style="
                  height: 100%;
                  display: flex;
                  justify-content: center;
                  flex-direction: column;
                "
                description="暂无数据"
              >
                <el-button type="primary" @click="startExam"
                  >开始考试</el-button
                >
              </a-empty>
            </div>
            <div class="exemBoxShow" v-else>
              <div
                style="
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                  margin-bottom: 18px;
                "
              >
                <span
                  >您并未通过该考试及格分，请点击右侧按钮重新参与！最近一次参与：成绩{{
                    tableData[tableData.length - 1].score
                  }}</span
                >
                <el-button type="primary" @click="startExam"
                  >开始考试</el-button
                >
              </div>
              <el-table
                :data="tableData"
                :header-cell-style="{ background: '#FAFAFA' }"
                v-loading="loading"
                style="width: 100%"
              >
                <el-table-column prop="date" type="index" label="序号">
                </el-table-column>
                <el-table-column prop="use_time" label="考试用时" width="180">
                  <template slot-scope="{ row }">
                    {{
                      row.use_time >= 60
                        ? parseInt(row.use_time / 60) +
                          "分钟" +
                          (row.use_time % 60) +
                          "秒"
                        : row.use_time + "秒"
                    }}
                  </template>
                </el-table-column>
                <el-table-column prop="create_time" label="提交时间">
                </el-table-column>
                <el-table-column prop="address" label="状态"> </el-table-column>
                <el-table-column prop="score" label="成绩"> </el-table-column>
                <el-table-column prop="address" align="center" label="操作">
                  <template slot-scope="{ row }">
                    <el-button type="text" @click="fjlist(row)">复卷</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
        <ul class="videoList">
          <el-button
            v-if="
              (!qyType('test') || !qyType('tjy') || !qyType('qdshjg2')) &&
              status != 0
            "
            class="practiceVideo"
            @click="startVideoPractice"
            type="primary"
            >视频练习</el-button
          >
          <li
            v-for="(item, index) in videoList"
            :key="index"
            :class="item.id == id ? 'videolistitem aivterLi' : 'videolistitem'"
            @click="changeLi(item)"
          >
            <aside
              style="
                margin-right: 14px;
                width: 150px;
                height: 100%;
                position: relative;
                padding: 0;
                overflow: hidden;
              "
              :class="Boolean(item.done) ? 'cardBox' : ''"
            >
              <img :src="item.cover_path" alt="" />
              <aside class="jiaobiao" style="padding: 0"></aside>
              <aside class="jiaobiaoText" style="padding: 0">已看完</aside>
            </aside>
            <div :title="item.title">
              <p>{{ item.title }}</p>

              <!-- <span>{{ item.create_time }}</span> -->
              <p style="width: 400px">
                <el-progress
                  :percentage="
                    Boolean(item.status && item.status != 0)
                      ? 100
                      : Boolean(item.done)
                      ? 100
                      : Number((item.mprogress * 100).toFixed(0))
                  "
                ></el-progress>
              </p>
            </div>
          </li>
          <li
            class="ksLisBox"
            @click="
              () => {
                if (this.aliDom)  {
                  this.Aliplayer.pause()
                } else {
                  this.$refs.videoPlayer.player.pause()
                }
                this.showVideo = false;
                this.id = '';
              }
            "
            v-if="
              Jurisdictions.随堂练习 &&
              Jurisdictions.随堂练习.模块展示 == '显示'
            "
          >
            <span class="ksListTitle">随堂考试</span>
            <div class="ksList">
              <span>考试</span>
              <p></p>
              <span
                >成绩:{{
                  tableData != 0
                    ? tableData[tableData.length - 1].score
                    : "暂无成绩"
                }}</span
              >
              <span>重新考试</span>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div
      style="
        position: absolute;
        top: 0;
        right: 0;
        height: 100vh;
        width: 100vw;
        z-index: 100000000;
        background: #fff;
      "
      v-if="disFace"
    >
      <face :comments="true" :show.sync="disFace"></face>
    </div>
    <!-- 常规验证码 1 , 运算二维码:2,滑动验证码:3,拼图验证码:4,选字验证码:5, -->

    <el-dialog
      title="验证码"
      :visible.sync="dialogVisible"
      width="384px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      :destroy-on-close="true"
    >
      <p>
        -剩余验证时间:<span style="font-size: 22px; color: #f00">{{
          uTime
        }}</span
        >秒
      </p>
      <!-- arith 算法选择，支持加、减、乘。设置为1至3分别代表加减乘，0为随机切换。 -->
      <Verify
        type="2"
        :arith="1"
        width="100%"
        @success="verifySuccess"
        @error="verifyError"
        :figure="10"
      ></Verify>
    </el-dialog>
  </div>
</template>

<script>
import Verify from "vue2-verify"; //验证码

import { MessageBox } from "element-ui";
import {
  materialList,
  materialaddlog,
  materiallearnlog,
  quizStart,
  getSetting,
  quizMylist,
  quizRedo,
  aliVodInfo,
  videoPractice,
  gzExamSetting,
  playInfo,
} from "@/api/admin.js";
import {
  getapplyid,
  getsubject_id,
  getGZ,
  setExectSetting,
  getisfacetimekjface,
  getcurrentInfo,
} from "@/utils/auth";
import eventBus from "@/utils/eventBus";
import { mapGetters } from "vuex";
import face from "@/components/PcFace";
import { learnImglist } from "@/utils/learnImg.js";
// 导出样式
import "aliyun-aliplayer/dist/skins/default/aliplayer-min.css";

import faceMode from "@/components/faceMode";
export default {
  components: {
    face,
    Verify,
  },
  computed: { ...mapGetters(["Jurisdictions", "initObj"]) },
  data() {
    return {
      videoTestSetting: {},
      ...faceMode.data,
      allplayertime: 0,
      dialogVisible: false,
      isdone: false,
      titleName: "",
      playerOptions: {
        playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
        autoplay: false, // 如果为true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 是否视频一结束就重新开始。
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: "zh-CN",
        aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: "video/mp4", // 类型
            src: "", // url地址
          },
        ],
        poster: "@/assets/logo/1.gif", // 封面地址
        notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: false, // 是否显示剩余时间功能
          fullscreenToggle: true, // 是否显示全屏按钮
        },
      },
      status: 0,
      limit: 1000, //单页视频个数
      videoList: [], //视频列表
      id: this.$route.query.id,
      subjctid: JSON.parse(JSON.stringify(this.$route.query.subjctid)),
      hoverStyle: "",
      loading: false,
      timeNow: 0, // 当前时间
      timeNowA: 0, // 当前时间
      overTime: 0, //看完是 1  没看完是0
      isFalse: true, //第一次进来
      type: this.$route.query.type,
      showVideo: true, //显示播放器
      tableData: [],
      isquerymodel: true, //开启快进
      face: getisfacetimekjface() ? JSON.parse(getisfacetimekjface()).face : "", //人脸图像
      loadingvideo: false,
      facetimeObj: Object,
      disFace: false,
      facetime: 0, //人脸验证时间

      http:
        process.env.NODE_ENV === "development"
          ? process.env.VUE_APP_BASE_API
          : window.location.href.slice(
              0,
              window.location.href.indexOf("/user")
            ),

      aliDom:false,
      Aliplayer: "",
      //阿里 播放器
      controlBarChildren: [
        { name: "progress", align: "blabs", x: 0, y: 44 }, //进度条
        { name: "playButton", align: "tl", x: 15, y: 12 }, //播放按钮
        { name: "timeDisplay", align: "tl", x: 10, y: 7 }, //播放时间
        { name: "fullScreenButton", align: "tr", x: 10, y: 12 }, //全屏按钮
        // {name:"subtitle", align:"tr",x:15, y:12},   //字幕
        { name: "speedButton", align: "tr", x: 15, y: 12 },
        { name: "qualityButton", align: "tr", x: 15, y: 12 },
        // {name:"setting", align:"tr",x:15, y:12,},  //设置
        { name: "volume", align: "tr", x: 5, y: 10 }, // 音量
      ],
      windowPcltime: null,
      uTime: 3 * 60, //未确定 自动退出时间 单位  秒
      windowTime: 0 * 60, //未操作 自动退出时间  单位 秒
      outTime: null, //退出定时器

      verifyNum: 0, //验证次数
    };
  },
  watch: {
    // overTime(val){
    //     if(val){
    //         this.addLog()
    //     }
    // }
    disFace(val) {
      this.$nextTick(() => {
        if (val) {
          clearTimeout(this.facetimeObj);
          if (this.windowTime && this.windowTime != 0) {
            this.OpenListening();
          }
        } else {
          // this.$refs.videoPlayer.player.play()
          this.$refs.videoPlayer.player.play();
          if (
            this.initObj.is_face &&this.Jurisdictions.gz&&
            JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjface ==
              "开启" &&
            JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjfacetime
          ) {
            let time = 0;
            if (
              JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
                .kjfacetime == "随机"
            ) {
              this.facetime =
                Math.floor(
                  Math.random() *
                    (Number(
                      JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
                        .kjfacetimeEnd
                    ) -
                      Number(
                        JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
                          .kjfacetimeStart
                      ) +
                      1)
                ) +
                Number(
                  JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
                    .kjfacetimeStart
                );
            } else if (
              JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
                .kjfacetime == "省厅规则"
            ) {
              this.facetime = 0;
              this.cyclesNum--;
              clearTimeout(this.facetimeObj);
            } else {
              this.facetime = JSON.parse(this.initObj.is_face)[
                this.Jurisdictions.gz
              ].kjfacetime;
            }
            this.faceTimePause(this.facetime * 60 * 1000);
          }
          // this.$refs.time.start()
        }
      });
    },
    timeNow(val, oval) {
      if (val && parseInt(val) != parseInt(oval)) {
        if (
          this.initObj.is_face &&this.Jurisdictions.gz&&
          JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjface ==
            "开启" &&
          JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjfacetime +
            ""
        ) {
          if (
            JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
              .kjfacetime == "省厅规则"
          ) {
            if (this.VerificationTime == parseInt(val)) {
              this.faceTimePause(1);
            }
            if (this.VerificationTime < parseInt(val)) {
              let num =
                this.allplayertime > 15 * 60
                  ? Math.floor(this.allplayertime / (15 * 60))
                  : 1;
              if (this.cyclesNum >= num) {
                this.faceTimePause(1);
              }
            }
            this.showFaceMode(this.allplayertime, this);
          }
        }
      }
    },
    allplayertime(val) {
      if (val) {
        if (
          this.initObj.is_face &&this.Jurisdictions.gz&&
          JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjface ==
            "开启" &&
          JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjfacetime +
            ""
        ) {
          if (
            JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
              .kjfacetime == "省厅规则"
          ) {
            let time = setTimeout(() => {
              faceMode.created(val, this); //获取验证次数
              clearTimeout(time);
            }, 1000);
          }
        }
      }
    },
  },
  methods: {
    ...faceMode.methods,
    notAlpay(time) {
      this.windowPcltime = setTimeout(() => {
        var setting = this.initObj?this.initObj.setting:''
        if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器')  {
          
          if(this.Aliplayer.fullscreenService.getIsFullScreen()){
            this.Aliplayer.fullscreenService.cancelFullScreen() || this.Aliplayer.exitFullscreen()
          }
          // this.Aliplayer.exitFullscreen&&this.Aliplayer.exitFullscreen();
        } else {
          
          this.$refs.videoPlayer.player.exitFullscreen();
        }

        this.CloseListening();
        clearTimeout(this.facetimeObj);
        clearTimeout(this.windowPcltime);
        // vifivecode
        if (
          JSON.parse(this.initObj.setting).vifivecode &&
          JSON.parse(this.initObj.setting).vifivecode == "验证码"
        ) {
          this.dialogVisible = true;
          this.outTime = setInterval(() => {
            // el-message-box__container
            if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器'){
              this.Aliplayer.pause();
            }else{
              this.$refs.videoPlayer.player.pause();
            }
            this.uTime--;
            this.$forceUpdate();
            if (this.uTime == 0) {
              clearInterval(this.outTime);
              this.dialogVisible = false;
              this.goback();
            }
          }, 1000);
        } else {
          this.$confirm(
            `您已${time}秒未操作界面~~~~~,请在一定时间内点击确认,否则将退出此界面 -剩余时间:<span style='font-size:22px;color:#f00;'>${this.uTime}</span>秒`,
            "警告",
            {
              confirmButtonText: "确定",
              type: "warning",
              showClose: false,
              showCancelButton: false,
              closeOnClickModal: false,
              closeOnPressEscape: false,
              dangerouslyUseHTMLString: true,
              callback: (action) => {
                this.faceTimePause(this.facetime * 60 * 1000);
                clearInterval(this.outTime);
                this.OpenListening();
              },
            }
          );
          this.outTime = setInterval(() => {
            // el-message-box__container
            this.uTime--;
            if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器'){
              this.Aliplayer.pause();
            }else{
              this.$refs.videoPlayer.player.pause();
            }
            document.querySelector(
              ".el-message-box__message"
              ).children[0].children[0].innerHTML = this.uTime;
            // document.querySelector(".el-message-box__message").children[0].innerHTML = `您已${time}秒未操作界面~~~~~,请在一定时间内点击确认,否则将退出此界面 -剩余时间:${this.uTime}秒`
            this.$forceUpdate();
            if (this.uTime <= 0) {
              clearInterval(this.outTime);
              MessageBox.close();
              this.goback();
            }
          }, 1000);
        }
        
        // setTimeout(()=>{
        // },3000)
      }, time * 1000);
    },
    OpenListening() {
      this.uTime = 3 * 60;
      window.addEventListener("mousedown", this.setTimeInfo);
      window.addEventListener("mousemove", this.setTimeInfo);
      window.addEventListener("keydown", this.setTimeInfo);
    },
    CloseListening() {
      window.removeEventListener("mousedown", this.setTimeInfo);
      window.removeEventListener("mousemove", this.setTimeInfo);
      window.removeEventListener("keydown", this.setTimeInfo);
    },
    setTimeInfo() {
      clearTimeout(this.windowPcltime);
      this.notAlpay(this.windowTime);
    },
    //验证码 成功
    verifySuccess() {
      this.verifyNum = 0;
      this.faceTimePause(this.facetime * 60 * 1000); //继续等待人脸验证
      this.dialogVisible = false;
      clearInterval(this.outTime);
      this.OpenListening();
    },
    //验证码 失败
    verifyError() {
      this.$message.error("验证码错误!!!");
      this.verifyNum++;
      if (this.verifyNum == 3) {
        this.$message.error("验证次数已达3次,将退出本次学习~~~~");
        clearInterval(this.outTime);
        this.dialogVisible = false;
        this.goback();
        this.verifyNum = 0;
      }
    },
    //人脸验证 开始
    faceTimePause(time) {
      if (time == 0) {
        return;
      }
      this.facetimeObj = setTimeout(() => {
        this.CloseListening();
        this.disFace = true;
        var isFull =
          document.webkitIsFullScreen ||
          document.mozFullScreen ||
          document.msFullscreenElement ||
          document.fullscreenElement;
        if (isFull == null || isFull == undefined) {
          isFull = false;
        }
        if (isFull) {
          var setting = this.initObj?this.initObj.setting:''
        if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器')  {
          if(this.Aliplayer.fullscreenService.getIsFullScreen()){
            this.Aliplayer.fullscreenService.cancelFullScreen() || this.Aliplayer.exitFullscreen()
          }
          } else {
            this.$refs.videoPlayer.player.exitFullscreen();
          }
        }

        var setting = this.initObj?this.initObj.setting:''
        if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器')  {
          this.Aliplayer.pause();
        } else {
          this.$refs.videoPlayer.player.pause();
        }
      }, time);
    },
    aliyunPlayerInfo(videoId) {
      aliVodInfo({
        videoId: videoId,
        // videoId: '18b05740250871ee87c734b6fdcb0302',
      }).then((res) => {
        if (res.code == 200) {
          this.Aliplayer.replayByVidAndPlayAuth(
            res.data.VideoMeta.VideoId,
            res.data.PlayAuth
          );
        } else {
          this.$toast.fail("视频初始化错误");
        }
      });
    },
    async startVideoPractice() {
      var setting = false;
      await gzExamSetting({
        gz: getGZ(),
      }).then((res) => {
        if (res.code == 200) {
          if (JSON.stringify(res.data) == "{}") {
            setting = true;
            return this.$message.error("该工种无考试设置");
          } else {
            this.videoTestSetting = res.data;
          }
        }
      });

      if (setting) {
        return;
      }
      await videoPractice({
        subjectid: getsubject_id(),
        material_id: this.id,
        // gz: getGZ(),
        applyid: getapplyid(),
      }).then((res) => {
        if (res.code == 200) {
          if (res.data.list.length == 0) {
            this.$message.error("该视频暂无试题");
          } else {
            this.$store.commit("SET_TI", res.data.list);
            this.$router.push(
              "/classroomVideoTest?quizid=" +
                res.data.quizid +
                "&gz=" +
                getGZ() +
                "&setting=" +
                JSON.stringify(this.videoTestSetting)
            );
          }
        } else {
          this.$message.error(res.msg);
        }
      });

      // videoPractice({
      //   subjectid: getsubject_id(),
      //   // gz: getGZ(),
      //   applyid: getapplyid(),
      // }).then((res) => {
      //   if (res.code == 200) {
      //     // console.log(res, "777");
      //     this.$store.commit("SET_TI", res.data.list);
      //     this.$router.push(
      //       "/videoPractice?quizid=" + res.data.quizid + "&gz=" + getGZ()
      //     );
      //   } else {
      //     this.$message.error(res.msg);
      //   }
      // });
    },
    async videoData() {
      await materialList({
        msid: this.subjctid,
        file_type: "视频",
        page: 1,
        limit: this.limit,
        applyid: getapplyid(),
      }).then((res) => {
        if (res.code == 200) {
          this.videoList = res.data.list;
          if (
            Object.keys(res.data).indexOf("scoreGqLimit") != -1 &&
            res.data.scoreGqLimit
          ) {
            this.overTime = 1;
            return this.$confirm("今天已学学时已达标，请明天继续学习", "提示", {
              type: "warning",
              showCancelButton: false,
              confirmButtonText: "返回",
              closeOnClickModal: false,
              closeOnPressEscape: false,
              showClose: false,
            }).then(() => {
              this.goback();
            });
          }
          this.videoList.map((item) => {
            if (item.id == this.id) {
              var setting = this.initObj?this.initObj.setting:''
              if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器')  {
                this.aliyunPlayerInfo(item.MediaId);
              } else {
                this.playerOptions.sources[0].src = item.file_path;
              }
              this.titleName = item.title;
              this.status = item.status;
              if (item.done == 1) {
                this.isdone = true;
              }
            }
            let list = JSON.parse(item.material_subject_full);
            if (!item.cover_path) {
              // console.log(list);
              for (let i = 0; i < learnImglist.length; i++) {
                for (let k = 0; k < list.length; k++) {
                  let el = list[k];
                  if (
                    el &&
                    el.indexOf(learnImglist[i].id) != -1 &&
                    (el.indexOf(learnImglist[i].id) -
                      el.indexOf(this.subjctid) <
                      2 ||
                      el.indexOf(learnImglist[i].id) -
                        el.indexOf(this.subjctid) >
                        2)
                  ) {
                    // console.log(123,'');
                    item.cover_path = learnImglist[i].src;
                    break;
                  }
                }
              }
            }
          });
        }
      });
    },
    //切换视频
    changeLi(item) {
      let subjctid = JSON.parse(JSON.stringify(this.$route.query.subjctid));
      let route = JSON.parse(JSON.stringify(this.$route.query.route));
      this.$router.push({
        query: {
          id: item.id,
          subjctid: subjctid,
          type: "视频",
          route: route,
          MediaId: item.MediaId,
        },
      });
      if (item.done == 1) {
        this.isdone = true;
        this.isFalse = false;
      } else {
        this.isFalse = true;
        this.isdone = false;
      }
      // this.playerReadied();
      if (this.overTime != 1) {
        this.addLog(1);
      }else{
        if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器')  {
          this.aliyunPlayerInfo(item.MediaId);
        } else {
          this.playerReadied();
          this.playerOptions.sources[0].src = item.file_path;
          this.$forceUpdate();
        }
      }
      this.overTime = 0;
      if (!this.showVideo) {
        this.showVideo = true;
      }
      this.status = item.status;
      this.id = item.id;
      this.titleName = item.title;
      var setting = this.initObj?this.initObj.setting:''
      
    },
    //播放结束
    async onPlayerEnded(player) {
      // console.log('123');
      // return
      this.isFalse = false;
      this.overTime = 1;
      await this.addLog(1);
      if (this.DialogVideoTest) {
        this.$confirm("您已看完当前视频，是否前往练题?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "success",
        })
          .then(() => {
            this.startVideoPractice();
          })
          .catch(() => {
            for (let index = 0; index < this.videoList.length; index++) {
              let item = this.videoList[index];
              if (item.id == this.id && this.videoList.length > index + 1) {
                this.changeLi(this.videoList[index + 1]);
                this.Aliplayer.play();
                break;
              }
            }
          });
        return;
      }
      for (let index = 0; index < this.videoList.length; index++) {
        let item = this.videoList[index];

        if (item.id == this.id && this.videoList.length > index + 1) {
          this.changeLi(this.videoList[index + 1]);
          this.$refs.videoPlayer.player.play();
          break;
        }
      }
    },
    //阿里 播放结束
    PlayerEnded() {
      this.isFalse = false;
      this.overTime = 1;
      this.addLog(1);
      for (let index = 0; index < this.videoList.length; index++) {
        let item = this.videoList[index];
        if (item.id == this.id && this.videoList.length > index + 1) {
          this.changeLi(this.videoList[index + 1]);
          this.Aliplayer.play();
          break;
        }
      }
    },
    // 当前播放位置发生变化时触发。
    onPlayerTimeupdate(player) {
      // console.log(player,'11111')
      this.timeNow = player.cache_.currentTime;
      this.allplayertime = this.$refs.videoPlayer.player.duration();
      // this.overTime = 0
      // if(player.cache_.duration-player.cache_.currentTime==8){
      //     this.overTime = 1
      // }
    },
    //阿里 当前播放位置发生变化时触发。
    PlayerTimeupdate() {
      // console.log(player.cache_.duration-player.cache_.currentTime)
      this.timeNow = this.Aliplayer.getCurrentTime();
      this.allplayertime = this.Aliplayer.getDuration();
    },
    //保存
    async addLog(data) {
      let duration = 100;
      let current = 0;
      var setting = this.initObj?this.initObj.setting:''
      if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器')  {
        duration = this.Aliplayer.getDuration();
        current = this.Aliplayer.getCurrentTime();
      } else {
        duration = this.$refs.videoPlayer.player.duration();
        current = this.$refs.videoPlayer.player.currentTime();
      }
      let mprogress = current / duration;

      // if (this.isdone || mprogress == 1) {
      //   mprogress = 1.0;
      // }

      mprogress = parseInt(mprogress * 100) / 100;

      // mprogress = mprogress.substr(0, mprogress.indexOf(".") + 3);

      let obj = {
        mprogress: mprogress,
        mid: this.id,
        msid: this.subjctid,
        period: this.timeNow,
        done: this.overTime,
        applyid: getapplyid(),
        face: this.face,
      };
      // console.log(obj);
      if (duration == 0) {
        return;
      }
      if (!data) {
        this.loading = true;
      }
      await materialaddlog(obj).then((res) => {
        if (res.code == 210) {
          this.DialogVideoTest = true;
        }
        this.loading = false;
        if (!data) return false;
        this.timeNow = 0;
        this.videoData();
      });

      await this.jlLog();
    },
    //获取学习记录
    async jlLog() {
      this.loadingvideo = true;
      await materiallearnlog({ applyid: getapplyid(), mid: this.id }).then(
        (res) => {
          this.loadingvideo = false;
          if (res.code == 200) {
            if (res.data.list.length != 0) {
              let isfor = false;
              res.data.list.map((item) => {
                if (item.done) {
                  isfor = true;
                }
              });
              if (isfor) {
                this.timeNowA = 0;
              } else {
                this.timeNowA = res.data.list[0].period;
              }
            } else {
              this.timeNowA = 0;
            }
          }
        }
      );
    },
    // 播放回调    每次开始播放就会执行  包括暂停之后、快进 快退
    onPlayerPlay(player) {},
    //阿里 视频初始化完成
    PlayerLoadeddata() {
      // this.loading=false
      // console.log(123);

      if (this.isFalse) {
        // alert(this.timeNowA)
        this.Aliplayer.seek(this.timeNowA);
      } else {
        this.Aliplayer.seek(0);
      }
      // let time = setTimeout(() => {
      //   if(this.initObj.is_face &&
      //     JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjface ==
      //       "开启" &&
      //     JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjfacetime){
      //       if(JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
      //       .kjfacetime == "省厅规则"){
      //         this.showFaceMode()
      //     }
      //   }
      //   clearTimeout(time);
      // }, 500);
    },
    //将侦听器绑定到组件的就绪状态。与事件监听器的不同之处在于，如果ready事件已经发生，它将立即触发该函数。。 每次仅在初始化的时候执行一次
    async playerReadied(player) {
      await this.jlLog();
      if (this.isFalse) {
        this.$refs.videoPlayer.player.currentTime(this.timeNowA);
      } else {
        this.$refs.videoPlayer.player.currentTime(0);
      }
      if (!this.isquerymodel) {
        document.getElementsByClassName("vjs-progress-control")[0].remove();
      }
      let time = setTimeout(() => {
        this.$refs.videoPlayer.player.play();

        clearTimeout(time);
      }, 500);
    },
    //返回
    goback() {
      this.$store.commit("SET_TAB", this.type);
      this.$router.push({
        path: this.$route.query.route,
        query: {
          subjct: this.subjctid,
        },
      });
    },
    //随堂练习 开始考试   getsubject_id()  getGZ()   getapplyid()
    startExam() {
      quizStart({
        subjectid: getsubject_id(),
        gz: getGZ(),
        applyid: getapplyid(),
      }).then((res) => {
        if (res.code == 200) {
          this.$store.commit("SET_TI", res.data.list);
          this.$router.push(
            "/classroomTest?quizid=" + res.data.quizid + "&gz=" + getGZ()
          );
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    //复卷
    fjlist(row) {
      this.loading = true;
      quizRedo({ quizid: row.id }).then((res) => {
        this.loading = false;
        if (res.code == 200) {
          this.$store.commit("SET_TI", res.data.list);
          this.$router.push(
            "/classroomTest?quizid=" + res.data.quizid + "&gz=fj"
          );
        }
      });
    },
  },
  created() {
    // var isFull =
    //   this.$refs.videoPlayer.player.webkitIsFullScreen() ||
    //   this.$refs.videoPlayer.player.mozFullScreen() ||
    //   this.$refs.videoPlayer.player.msFullscreenElement() ||
    //   this.$refs.videoPlayer.player.fullscreenElement();
    var setting = this.initObj?this.initObj.setting:''
    if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器'){
      this.aliDom = true
    }else{
      this.aliDom = false
    }
    setTimeout(() => {
      if (
        this.initObj.is_face &&this.Jurisdictions.gz&&
        JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjface ==
          "开启" &&
        JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz].kjfacetime
      ) {
        if (
          navigator.getUserMedia ||
          (navigator.mediaDevices && navigator.mediaDevices.getUserMedia)
        ) {
          let time = 0;
          if (
            JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
              .kjfacetime == "随机"
          ) {
            this.facetime =
              Math.floor(
                Math.random() *
                  (Number(
                    JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
                      .kjfacetimeEnd
                  ) -
                    Number(
                      JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
                        .kjfacetimeStart
                    ) +
                    1)
              ) +
              Number(
                JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
                  .kjfacetimeStart
              );
          } else if (
            JSON.parse(this.initObj.is_face)[this.Jurisdictions.gz]
              .kjfacetime == "省厅规则"
          ) {
            this.facetime = 0;
          } else {
            this.facetime = JSON.parse(this.initObj.is_face)[
              this.Jurisdictions.gz
            ].kjfacetime;
          }
          this.faceTimePause(this.facetime * 60 * 1000);
        } else {
          this.$alert("该电脑没有摄像头，无法使用该模块", "提示", {
            confirmButtonText: "确定",
            callback: () => {
              this.$router.go(-1);
            },
          });
        }
      }
    }, 1000);
    this.isquerymodel = JSON.parse(this.initObj.setting).vadioSick
      ? !(JSON.parse(this.initObj.setting).vadioSick == "关闭")
      : false;
    if (JSON.parse(getcurrentInfo()).drag_video_progress) {
      this.isquerymodel =
        JSON.parse(getcurrentInfo()).drag_video_progress == "开启";
    }
    if (!this.isquerymodel) {
    if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器')  {
        this.controlBarChildren = this.controlBarChildren.filter(
          (item) => item.name != "progress"
        ); //禁用进度条快进
      } else {
        this.playerOptions.playbackRates = [1.0];
      }
    }
    // this.jlLog()
    this.$store.commit("DEL_TI");
    this.overTime = 0;
    getSetting({ subjectid: getsubject_id(), gz: getGZ() }).then((res) => {
      if (res.code == 200) {
        this.obj = res.data.随堂练习;
        setExectSetting(Object.assign(this.obj));
      }
    });
    quizMylist({ applyid: getapplyid() }).then((res) => {
      if (res.code == 200) {
        this.tableData = res.data.list;
      }
    });
    // window.addEventListener('unload',this.onunload)
  },
  beforeDestroy() {
    if (this.showVideo && !this.overTime) {
      this.addLog();
    }
    this.CloseListening();
    clearTimeout(this.windowPcltime);
    var setting = this.initObj?this.initObj.setting:''
    if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器')  {
      this.Aliplayer.off("ended", this.PlayerEnded);
      this.Aliplayer.off("canplay", this.PlayerLoadeddata);
      this.Aliplayer.off("timeupdate", this.PlayerTimeupdate);
      this.Aliplayer.dispose();
    }
    
  },
  async mounted() {
    var setting = this.initObj?this.initObj.setting:''
    if (setting&&JSON.parse(setting).video_box&&JSON.parse(JSON.parse(setting).video_box)[getGZ()]=='阿里播放器') {
      var that = this;
      Aliplayer.__unable2Anti9Debugger13Key = "error";
      this.loading = true;
      await aliVodInfo({
        videoId: 
          this.$route.query.MediaId,
      }).then((res) => {
        if (res.code == 200) {
          new Aliplayer(
            {
              controlBarVisibility: "hover",
              showBarTime: "5000",
              id: "J_prismPlayer",
              vid: res.data.VideoMeta.VideoId,
              // diagnosisButtonVisible:false, // 诊断按钮
              keyShortCuts: true, //快捷键
              // encryptType: 1, //当播放私有加密流时需要设置本参数值为1。其它情况无需设置。
              playConfig: {
                // EncryptType: "AliyunVoDEncryption",
                PlayDomain: "video.taijieyun.com",
              },
              defaultDefinition:'LD',
              definition:that.initObj.hd_video.includes(getGZ())?'FD,LD,SD':'FD,LD',
              playauth: res.data.PlayAuth, //视频的播放凭证，可以在通用媒体管理服务控制台获取。
              skinLayout: [
                { name: "bigPlayButton", align: "blabs", x: 30, y: 80 },
                {
                  name: "H5Loading",
                  align: "cc",
                },
                { name: "errorDisplay", align: "tlabs", x: 0, y: 0 },
                { name: "infoDisplay" },
                { name: "tooltip", align: "blabs", x: 0, y: 56 },
                { name: "thumbnail" },
                {
                  name: "controlBar",
                  align: "blabs",
                  x: 0,
                  y: 0,
                  children: that.controlBarChildren,
                },
              ],
              components: this.isquerymodel
                ? [
                    {
                      name: "QualityComponent",
                      type: AliPlayerComponent.QualityComponent,
                      // args: [function(definition,desc) {
                      //   console.log(definition + '-----' + desc)
                      // }]
                    },
                    {
                      name: "RateComponent",
                      type: AliPlayerComponent.RateComponent,
                    },
                  ]
                : [
                    {
                      name: "QualityComponent",
                      type: AliPlayerComponent.QualityComponent,
                      // args: [function(definition,desc) {
                      //   console.log(definition + '-----' + desc)
                      // }]
                    },
                  ],
            },
            async function (player) {
              await that.jlLog();
              // console.log();
              // console.log(AliPlayerComponent);
              player.on("error", (e) => {
                that.loading = false;
              });
              // player.on("sourceloaded", function (params) {
              //   // var paramData = params.paramData;
              //   // var desc = paramData.desc;
              //   // var definition = paramData.definition;
              //   console.log(params,'09888');
                
              // });
              player
                .getComponent("QualityComponent")
                .setCurrentQuality('标清','LD');
              that.Aliplayer = player;
              that.Aliplayer.on("ready", that.PlayerLoadeddata);
              that.Aliplayer.on("canplay", () => {
                that.loading = false;
              });
              that.Aliplayer.on("timeupdate", that.PlayerTimeupdate);
              that.Aliplayer.on("ended", that.PlayerEnded);
              that.Aliplayer.play();
            }
          );
        } else {
          this.$toast.fail("视频初始化错误");
        }
      });
    } else {
      document.getElementsByClassName("vjs-progress-control")[0].remove();
    }
    let NotOperated = JSON.parse(this.initObj.setting).NotOperated;
    this.windowTime = NotOperated * 60;
    if (this.windowTime && this.windowTime != 0) {
      this.OpenListening();
      // this.notAlpay(this.windowTime);
    }
    // this.OpenListening()
    // this.notAlpay(this.windowTime)
    this.videoData();
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/utis.scss";
aside {
  background: transparent;
  padding: 0;
  margin: 0;
  border-radius: 0;
  line-height: 1;
}
.videoTitle {
  font-size: 20px;
  color: #333;
  margin-bottom: 24px;
}
.videoBigBox {
  display: flex;
  justify-content: space-between;
  height: calc(100vh - 200px);
  padding: 18px 0;
  .videoList {
    ::v-deep {
      .practiceVideo {
        width: 100%;
      }
    }
    padding: 18px 0;
    width: 400px;
    margin-left: 24px;
    // background: #f0f;
    overflow: auto;
    overflow-x: hidden;
    height: 100%;
    &::-webkit-scrollbar {
      width: 5px;
    }
    &::-webkit-scrollbar-track {
      width: 5px;
      background: #eee;
    }
    &::-webkit-scrollbar-thumb {
      width: 5px;
      background: #ccc;
    }
    // box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    .ksLisBox {
      height: 110px;
      display: flex;
      margin-top: 14px;
      cursor: pointer;
      flex-direction: column;
      justify-content: space-between;
      background: rgba(23, 93, 255, 0.08);
      padding: 27px 21px;
      .ksListTitle {
        margin: 0;
        color: #333;
        font-size: 16px;
      }
      .ksList {
        width: 166px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        p {
          margin: 0;
          height: 16px;
          width: 1px;
          background: #175dff;
        }
        span {
          color: #175dff;
        }
      }
    }
    .videolistitem {
      height: 100px;
      display: flex;
      margin-top: 14px;
      cursor: pointer;

      &:hover {
        p {
          color: #175dff;
        }
      }
      &:first-child {
        margin-top: 10px;
      }
      img {
        height: 100%;
        width: 100%;
      }
      div {
        width: calc(100% - 150px - 21px - 14px);
        p {
          margin: 0;
          color: #333;
          margin-bottom: 18px;
          font-size: 16px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
        span {
          color: #999;
        }
      }
    }
    .jiaobiao {
      display: none;
      position: absolute;
      top: 20px;
      right: -80px;
      transform: rotate(40deg);
      background: #f00;
      // padding:10px;
      height: 30px;
      width: 200px;
    }
    .jiaobiaoText {
      display: none;
      position: absolute;
      // padding:10px;
      transform: rotate(40deg);
      top: 15px;
      right: 15px;
      color: #fff;
    }
    .cardBox {
      .jiaobiao {
        display: block;
      }
      .jiaobiaoText {
        display: block;
      }
    }
    .aivterLi {
      p {
        color: #175dff !important;
      }
    }
  }
  .videoBox {
    flex: 1;
    .exemBox {
      padding: 30px;
      height: 100%;
      .exemBoxShow {
        height: 100%;
        width: 100%;
        // background: #f0f;
      }
    }
  }
}
::v-deep {
  .varify-input-code {
    background: #eee !important;
  }
  .el-dialog__body {
    height: 220px !important;
    padding-top: 0 !important;
  }
  .video-js .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-hover,
  .video-js .vjs-volume-panel.vjs-volume-panel-horizontal:hover,
  .video-js .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-slider-active {
    width: 10em;
    -webkit-transition: width 0.1s;
    transition: width 0.1s;
  }
  .video-js *:focus:not(:focus-visible) {
    outline: none;
  }
  .video-js
    .vjs-volume-panel.vjs-hover
    .vjs-volume-control.vjs-volume-horizontal,
  .video-js .vjs-volume-panel:hover .vjs-volume-control.vjs-volume-horizontal,
  .video-js .vjs-volume-panel:focus .vjs-volume-control.vjs-volume-horizontal,
  .video-js .vjs-volume-panel .vjs-volume-control:active.vjs-volume-horizontal,
  .video-js
    .vjs-volume-panel.vjs-hover
    .vjs-mute-control
    ~ .vjs-volume-control.vjs-volume-horizontal,
  .video-js
    .vjs-volume-panel
    .vjs-volume-control.vjs-slider-active.vjs-volume-horizontal {
    width: 5em;
    height: 3em;
    margin-right: 0;
  }
  .video-js .vjs-volume-panel.vjs-hover .vjs-volume-control,
  .video-js .vjs-volume-panel:hover .vjs-volume-control,
  .video-js .vjs-volume-panel:focus .vjs-volume-control,
  .video-js .vjs-volume-panel .vjs-volume-control:hover,
  .video-js .vjs-volume-panel.vjs-hover .vjs-mute-control ~ .vjs-volume-control,
  .video-js .vjs-volume-panel .vjs-volume-control.vjs-slider-active {
    opacity: 1;
  }
}
.isShowModel {
  ::v-deep {
    .vjs-progress-control {
      display: none !important;
      content: none;
    }
  }
}
</style>
